package net.ib.mtalk.ui.attachment.vcard;

import java.util.ArrayList;
import java.util.List;

import net.ib.mtalk.R;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;

/**
 * 주소록에서 선택된 사람의 Raw_Contact Uri 를 받아 와서 데이터를 뽑아낸다.
 * @author happy2v
 */
public class ContactAccessor {
	
	private static ContactAccessor contactAccessor = null;
	
	public static ContactAccessor getInstance(){
		if(contactAccessor == null){
			contactAccessor = new ContactAccessor();
		}
		return contactAccessor;
	}
	
	public Intent getPickContactIntent(){
		return new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
	}
	
	public ContactStruct loadContact(ContentResolver contentResolver, Uri contactUri){
		
		ContactStruct contactInfo = new ContactStruct();
		
		// 쿼리문 재사용 변수들(주의해서 사용)
		String[] projection;
		String[] selectionArgs;
		String selectionBase;
		String selection;
		String sortOrder;
		
		// raw_contact 를 저장할 변수
		long contactId = -1;
		
		// 아이디 저장
		projection = new String[]{Contacts._ID};
		selectionArgs = null;
		selection = null;
		sortOrder = null;
		Cursor idCursor = contentResolver.query(contactUri, projection, selection, selectionArgs, sortOrder);
		try{
			if(idCursor.moveToFirst()){
				contactId = idCursor.getLong(idCursor.getColumnIndexOrThrow(Contacts._ID));
			}
		}finally{
			idCursor.close();
		}

		/**
		 * 쿼리문 공통 설정
		 */
		selectionArgs = new String[] {String.valueOf(contactId)};
		selectionBase = Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='";
		sortOrder = null;

		/**
		 * 이름 설정
		 */
		projection = new String[]{ StructuredName.GIVEN_NAME, StructuredName.DISPLAY_NAME };
		selection = selectionBase + StructuredName.CONTENT_ITEM_TYPE + "'";
		Cursor nameCursor = contentResolver.query(Data.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		try{			
			while(nameCursor.moveToNext()){
				if(nameCursor.getString(nameCursor.getColumnIndexOrThrow(StructuredName.GIVEN_NAME)) != null){
					contactInfo.name = nameCursor.getString(nameCursor.getColumnIndexOrThrow(StructuredName.GIVEN_NAME));
				}
				if(nameCursor.getString(nameCursor.getColumnIndexOrThrow(StructuredName.DISPLAY_NAME)) != null){
					contactInfo.fullName = nameCursor.getString(nameCursor.getColumnIndexOrThrow(StructuredName.DISPLAY_NAME));
				}
			}
		}finally{
			nameCursor.close();
		}
		
		/**
		 * 사진 설정
		 */
		projection = new String[]{ Photo.PHOTO };
		selection = selectionBase + Photo.CONTENT_ITEM_TYPE + "'";
		Cursor photoCursor = contentResolver.query(Data.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		try{
			while(photoCursor.moveToNext()){
				if(photoCursor.getBlob(photoCursor.getColumnIndexOrThrow(Photo.PHOTO)) != null){
					contactInfo.setPhoto(photoCursor.getBlob(photoCursor.getColumnIndexOrThrow(Photo.PHOTO)), "PNG");
				}
			}
		}finally{
			photoCursor.close();
		}
		
		/**
		 * 전화번호 리스트 추가
		 */
		projection = new String[]{ Phone.TYPE, Phone.NUMBER, Phone.LABEL };
		selection = selectionBase + Phone.CONTENT_ITEM_TYPE + "'";
		Cursor phoneCursor = contentResolver.query(Data.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		try{
			while(phoneCursor.moveToNext()){
				contactInfo.addPhone(
						phoneCursor.getInt(phoneCursor.getColumnIndexOrThrow(Phone.TYPE)), 
						phoneCursor.getString(phoneCursor.getColumnIndexOrThrow(Phone.NUMBER)), 
						phoneCursor.getString(phoneCursor.getColumnIndexOrThrow(Phone.LABEL)), 
						false);
			}
		}finally{
			phoneCursor.close();
		}
		
		/**
		 * 이메일 리스트 추가
		 */
		projection = new String[]{ Email.TYPE, Email.DATA1, Email.LABEL };
		selection = selectionBase + Email.CONTENT_ITEM_TYPE + "'";
		Cursor emailCursor = contentResolver.query(Email.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		try{
			while(emailCursor.moveToNext()){
				contactInfo.addEmail(
						emailCursor.getInt(emailCursor.getColumnIndexOrThrow(Email.TYPE)),
						emailCursor.getString(emailCursor.getColumnIndexOrThrow(Email.DATA1)),
						emailCursor.getString(emailCursor.getColumnIndexOrThrow(Email.LABEL)),
						false);
			}
		}finally{
			emailCursor.close();
		}
		
		/**
		 * 주소 리스트 추가
		 */
		projection = new String[]{ StructuredPostal.FORMATTED_ADDRESS,
				StructuredPostal.TYPE, StructuredPostal.LABEL, StructuredPostal.STREET,
				StructuredPostal.POBOX, StructuredPostal.NEIGHBORHOOD, StructuredPostal.CITY,
				StructuredPostal.REGION, StructuredPostal.POSTCODE, StructuredPostal.COUNTRY };
		selection = selectionBase + StructuredPostal.CONTENT_ITEM_TYPE + "'";
		Cursor postalCursor = contentResolver.query(StructuredPostal.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		try{
			while(postalCursor.moveToNext()){
				List<String> postalPartList = new ArrayList<String>();
				postalPartList.add(postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.STREET)));
				postalPartList.add(postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.POBOX)));
				postalPartList.add(postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.NEIGHBORHOOD)));
				postalPartList.add(postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.CITY)));
				postalPartList.add(postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.REGION)));
				postalPartList.add(postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.POSTCODE)));
				postalPartList.add(postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.COUNTRY)));
				contactInfo.addPostal(
						postalCursor.getInt(postalCursor.getColumnIndexOrThrow(StructuredPostal.TYPE)),
						postalPartList,
						postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.LABEL)),
						postalCursor.getString(postalCursor.getColumnIndexOrThrow(StructuredPostal.FORMATTED_ADDRESS)),
						false);
			}
		}finally{
			postalCursor.close();
		}
		
		/**
		 * 메신져 리스트 추가
		 */
		projection = new String[]{ Im.PROTOCOL, Im.CUSTOM_PROTOCOL, Im.TYPE, 
				Im.DATA, Im.LABEL };
		selection = selectionBase + Im.CONTENT_ITEM_TYPE + "'";
		Cursor imCursor = contentResolver.query(Data.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		try{
			while(imCursor.moveToNext()){
				contactInfo.addImData(
						Integer.parseInt(imCursor.getString(imCursor.getColumnIndexOrThrow(Im.PROTOCOL))),
						imCursor.getString(imCursor.getColumnIndexOrThrow(Im.CUSTOM_PROTOCOL)),
						imCursor.getInt(imCursor.getColumnIndexOrThrow(Im.TYPE)),
						imCursor.getString(imCursor.getColumnIndexOrThrow(Im.DATA)),
						imCursor.getString(imCursor.getColumnIndexOrThrow(Im.LABEL)),
						false);
			}
		}finally{
			imCursor.close();
		}
		
		/**
		 * 조직도 리스트 추가
		 */
		projection = new String[]{ Organization.TYPE, Organization.TITLE,
				Organization.DEPARTMENT, Organization.JOB_DESCRIPTION,
				Organization.SYMBOL, Organization.PHONETIC_NAME,
				Organization.OFFICE_LOCATION, Organization.DATA10,
				Organization.LABEL, Organization.COMPANY };
		selection = selectionBase + Organization.CONTENT_ITEM_TYPE + "'";
		Cursor organizationCursor = contentResolver.query(Data.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		try{
			while(organizationCursor.moveToNext()){
				List<String> organizationPartList = new ArrayList<String>();
				organizationPartList.add(organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.TITLE)));
				organizationPartList.add(organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.DEPARTMENT)));
				organizationPartList.add(organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.JOB_DESCRIPTION)));
				organizationPartList.add(organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.SYMBOL)));
				organizationPartList.add(organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.PHONETIC_NAME)));
				organizationPartList.add(organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.OFFICE_LOCATION)));
				organizationPartList.add(organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.DATA10)));
				contactInfo.addOrganization(
						organizationCursor.getInt(organizationCursor.getColumnIndexOrThrow(Organization.TYPE)),
						organizationPartList,
						organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.LABEL)),
						organizationCursor.getString(organizationCursor.getColumnIndexOrThrow(Organization.COMPANY)),
						false);
			}
		}finally{
			organizationCursor.close();
		}
		
		/**
		 * 메모 리스트 추가
		 */
		projection = new String[]{ Note.NOTE };
		selection = selectionBase + Note.CONTENT_ITEM_TYPE + "'";
		Cursor noteCursor = contentResolver.query(Data.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		try{
			while(noteCursor.moveToNext()){
				if(!noteCursor.getString(noteCursor.getColumnIndexOrThrow(Note.NOTE)).equals("")){
					contactInfo.addNote(noteCursor.getString(noteCursor.getColumnIndexOrThrow(Note.NOTE)), false);
				}
			}
		}finally{
			noteCursor.close();
		}
		
		if(contactInfo.name == null){
			if(contactInfo.company != null){
				contactInfo.name = contactInfo.company;
	        }else if(contactInfo.title != null){
	        	contactInfo.name = contactInfo.title;
	        }else if(contactInfo.phoneList != null){
	        	contactInfo.name = contactInfo.phoneList.get(0).number;
	        }else if(contactInfo.emailList != null){
	        	contactInfo.name = contactInfo.emailList.get(0).address;
	        }else if(contactInfo.imList != null){
	        	contactInfo.name = contactInfo.imList.get(0).data;
	        }else if(contactInfo.organizationList != null){
	        	contactInfo.name = contactInfo.organizationList.get(0).company;
	        }else if(contactInfo.noteList != null){
	        	contactInfo.name = contactInfo.noteList.get(0).note;
	        }else if(contactInfo.postalList != null){
	        	contactInfo.name = contactInfo.postalList.get(0).formattedAddress;
	        }else{
	        	contactInfo.name = "Name";
	        }
		}
		if(contactInfo.fullName == null){
			if(contactInfo.company != null){
				contactInfo.name = contactInfo.company;
	        }else if(contactInfo.title != null){
	        	contactInfo.name = contactInfo.title;
	        }else if(contactInfo.phoneList != null){
	        	contactInfo.name = contactInfo.phoneList.get(0).number;
	        }else if(contactInfo.emailList != null){
	        	contactInfo.name = contactInfo.emailList.get(0).address;
	        }else if(contactInfo.imList != null){
	        	contactInfo.name = contactInfo.imList.get(0).data;
	        }else if(contactInfo.organizationList != null){
	        	contactInfo.name = contactInfo.organizationList.get(0).company;
	        }else if(contactInfo.noteList != null){
	        	contactInfo.name = contactInfo.noteList.get(0).note;
	        }else if(contactInfo.postalList != null){
	        	contactInfo.name = contactInfo.postalList.get(0).formattedAddress;
	        }else{
	        	contactInfo.name = "Name";
	        }
		}
		return contactInfo;
	}
}